<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;

class ArticleCateController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'ArticleCate';

        $this->defaultOrder = [
            ['filed' => 'sorting', 'order' => 'ASC'],
            ['filed' => 'created_at', 'order' => 'desc'],
        ];
    }

    /**
     * List
     */
    public function list(Request $request)
    {
        $param = $request->all();

        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $orders = $this->defaultOrder;
        $where = $this->getFilterWhere($request);
        if ($this->defaultWhere) {
            $where = array_merge($this->defaultWhere, $where);
        }

        $query = $model->query();
        foreach ($where as $value) {
            $query->where($value[0], $value[1], $value[2]);
        }
        foreach ($orders as $order) {
            $query->orderBy($order['filed'], $order['order']);
        }
        $list = $query->get()->toArray();
        if ($list) {
            // 处理列表数据
            $list = $this->handleListData($list);
        }
        $data = [
            'data' => $list,
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * Eval data for post data save
     *
     * @param Request $request
     * @return array
     */
    protected function evalData($request)
    {
        $param = $request->all();

        $data = [
            'id' => $param['id'],
            'parent_id' => $param['parent_id'] ?: 0,
            'name' => $param['name'],
            'sub_name' => $param['sub_name'],
            'sorting' => $param['sorting'],
            'status' => $param['status'],
        ];

        return $data;
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);
        $data = list_to_tree($data, 'id', 'parent_id', 'children', 0);

        return $data;
    }
}
